//
//  AppDelegate.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/18.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "MainTabBarController.h"
#import "MainNavigationController.h"
#import "BoundTelViewController.h"
#import <AMapFoundationKit/AMapServices.h>
#import "WXApi.h"
#import "WXApiManager.h"
#import "PaymentManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import <JMessage/JMessage.h>
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#import "JCHATFileManager.h"
#import "ZSGuidePageController.h"
#import "ShopTabBarController.h"

#endif

@interface AppDelegate ()<WXApiDelegate,JPUSHRegisterDelegate,JMessageDelegate,UITabBarControllerDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 启动图片延时: 1秒
    [NSThread sleepForTimeInterval:1];
    
    [AMapServices sharedServices].apiKey = MapKey;
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
//    MainNavigationController * navVC = [[MainNavigationController alloc] initWithRootViewController:[LoginViewController new]];
    
    if ([self isNewVersion]) {
    
        self.window.rootViewController = [[ZSGuidePageController alloc] init];
    }else{

        NSString * shop_id = DEF_GET_OBJECT(@"shopid");
        
        if (shop_id) {
            
            ShopTabBarController * tabs = [[ShopTabBarController alloc] init];
            tabs.delegate = self;
            self.window.rootViewController = tabs;
            
//            [self updateIMData];
        }else{
          
            NSString * ID = DEF_GET_OBJECT(@"id");
            
            if (ID) {
                
                MainTabBarController *tabs = [[MainTabBarController alloc] init];
                tabs.delegate = self;
                self.window.rootViewController = tabs;
                
//                [self updateIMData];
            }else{
                
                self.window.rootViewController = [LoginViewController new];
            }
        }
       
    }

    
    [self.window makeKeyAndVisible];

    [WXApi registerApp:@"wxe282ff941e1f8a1d"];
    
    NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:30  * 1024 * 1024 diskPath:nil];
    
    [NSURLCache setSharedURLCache:cache];
    
    // Required - 启动 JMessage SDK
//    [JMessage setupJMessage:launchOptions appKey:@"" channel:nil apsForProduction:NO category:nil];
//    // Required - 注册 APNs 通知
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        //可以添加自定义categories
//        [JMessage registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
//                                                      UIUserNotificationTypeSound |
//                                                      UIUserNotificationTypeAlert)
//                                          categories:nil];
//    } else {
//        //categories 必须为nil
//        [JMessage registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
//                                                      UIRemoteNotificationTypeSound |
//                                                      UIRemoteNotificationTypeAlert)
//                                          categories:nil];
//    }
//
    //极光推送
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    [JPUSHService setupWithOption:launchOptions appKey:@"e247c401cfa87e24fd2ab961"
                          channel:@"Publish channel"
                 apsForProduction:NO
            advertisingIdentifier:nil];  // 这里是没有advertisingIdentifier的情况，有的话，大家在自行添加
    //注册远端消息通知获取device token
    [application registerForRemoteNotifications];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode,NSString*registrationID) {

        if(resCode ==0){
            
            DEF_SET_OBJECT(registrationID, @"registrationID");
        }else{

            NSLog(@"registrationID获取失败，code：%d",resCode);

        }

    }];

    
    //极光IM
    [JMessage addDelegate:self withConversation:nil];
    
    [JMessage setupJMessage:launchOptions appKey:@"e247c401cfa87e24fd2ab961" channel:@"Publish channel" apsForProduction:YES category:nil messageRoaming:YES];
    
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JMessage registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                      UIUserNotificationTypeSound |
                                                      UIUserNotificationTypeAlert) categories:nil];
    }
    else {
        //categories 必须为nil
        [JMessage registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                      UIUserNotificationTypeSound |
                                                      UIUserNotificationTypeAlert) categories:nil];
    }
    
    [JCHATFileManager initWithFilePath];
    [JMessage resetBadge];
    return YES;
}


//- (void)updateIMData{
//
//    NSString * user_id = DEF_GET_OBJECT(@"id");
//    [[ZRNetworkTool sharedTool] getUserInfoResultWithUser_id:user_id WithExamine_user_id:@"" WithBlock:^(BOOL success, id responseData) {
//
//        if (success) {
//
//            NSDictionary * dict = responseData[@"data"];
//            NSString * phone = [NSString stringWithFormat:@"%@",dict[@"phone"]];
//            NSString * user_name = [NSString stringWithFormat:@"%@",dict[@"user_name"]];
//            int jiguang_register_status = [dict[@"jiguang_register_status"] intValue];
//
//            NSString * imgStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,dict[@"head_img"]];
//            DEF_SET_OBJECT(imgStr, @"imgStr");
//
//            NSURL * url = [NSURL URLWithString:imgStr];
//            //            UIImage * imaa = [UIImage ];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//
//            [JMSGUser updateMyInfoWithParameter:user_name userFieldType:kJMSGUserFieldsNickname completionHandler:^(id resultObject, NSError *error) {
//
//                if (error == nil) {
//
//                    //                    NSLog(@"修改成功");
//
//                } else {
//                    //                    NSLog(@"修改失败");
//
//                }
//            }];
//
//            [JMSGUser updateMyInfoWithParameter:data userFieldType:kJMSGUserFieldsAvatar completionHandler:^(id resultObject, NSError *error) {
//
//                if (error == nil) {
//                    //                    NSLog(@"===shanghcuan");
//                    //                    [MBProgressHUD showMessage:@"上传成功" view:self.view];
//                } else {
//                    //                    NSLog(@"===shibai");
//                    //                    [MBProgressHUD showMessage:@"上传失败!" view:self.view];
//                }
//            }];
//
//
//            if (jiguang_register_status == 1) {
//
//                [JMSGUser loginWithUsername:phone password:phone completionHandler:^(id resultObject, NSError *error) {
//
//                    if (error == nil) {
//
//                    }
//                }];
//            }else{
//
//                JMSGUserInfo *info = [[JMSGUserInfo alloc]init];
//                info.nickname = user_name;
//
//                [JMSGUser registerWithUsername:phone password:phone userInfo:info completionHandler:^(id resultObject, NSError *error) {
//                    if (!error) {
//                        //注册成功
//                        [[ZRNetworkTool sharedTool] updateUserInfoWithUpdate_Class:@"jiguang_register_status" WithUpdate_content:@"1" WithBlock:^(BOOL success, id responseData) {
//
//                            if (success) {
//
//                                NSLog(@"注册成功");
//                            }
//                        }];
//                    } else {
//                        //注册失败
//                    }
//                }];
//            }
//        }
//    }];
//}

- (BOOL)isNewVersion{
    
    NSDictionary * info = [NSBundle mainBundle].infoDictionary;
    
    NSString * currentVersion = info[@"CFBundleShortVersionString"];
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    
    NSString * oldVersion = [defaults objectForKey:@"app_version"];
    
    if ([currentVersion isEqualToString:oldVersion]) {
        
        return NO;
    }else{
        
        [defaults setObject:currentVersion forKey:@"app_version"];
        
        [defaults synchronize];
        
        return YES;
    }
}

    
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    [JMessage registerDeviceToken:deviceToken];
}


#pragma mark - JPUSHRegisterDelegate
// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}

//MARK: - JMessage Delegate
- (void)onReceiveNotificationEvent:(JMSGNotificationEvent *)event{
    SInt32 eventType = (JMSGEventNotificationType)event.eventType;
    switch (eventType) {
        case kJMSGEventNotificationCurrentUserInfoChange:{
            NSLog(@"Current user info change Notification Event ");
        }
            break;
        case kJMSGEventNotificationReceiveFriendInvitation:
        case kJMSGEventNotificationAcceptedFriendInvitation:
        case kJMSGEventNotificationDeclinedFriendInvitation:
        case kJMSGEventNotificationDeletedFriend:
        {
            //JMSGFriendNotificationEvent *friendEvent = (JMSGFriendNotificationEvent *)event;
            NSLog(@"Friend Notification Event");
        }
            break;
        case kJMSGEventNotificationReceiveServerFriendUpdate:
            NSLog(@"Receive Server Friend update Notification Event");
            break;
            
            
        case kJMSGEventNotificationLoginKicked:
            NSLog(@"LoginKicked Notification Event ");
        case kJMSGEventNotificationServerAlterPassword:{
            if (event.eventType == kJMSGEventNotificationServerAlterPassword) {
                NSLog(@"AlterPassword Notification Event ");
            }
        case kJMSGEventNotificationUserLoginStatusUnexpected:
            if (event.eventType == kJMSGEventNotificationServerAlterPassword) {
                NSLog(@"User login status unexpected Notification Event ");
            }
            
        }
            break;
            
        default:
            break;
    }
}

- (void)onDBMigrateStart {
    NSLog(@"onDBmigrateStart in appdelegate");
    _isDBMigrating = YES;
}

- (void)onDBMigrateFinishedWithError:(NSError *)error {
    NSLog(@"onDBmigrateFinish in appdelegate");
    _isDBMigrating = NO;
//    [[NSNotificationCenter defaultCenter] postNotificationName:kDBMigrateFinishNotification object:nil];
}


//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//    // Required - 注册token
//    [JMessage registerDeviceToken:deviceToken];
//}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
////    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
//    [WXApi handleOpenURL:url delegate:self];
//    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
//    return YES;
//}


//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//    }else{
//
//        [WXApi handleOpenURL:url delegate:self];
//        [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
//    }
//
//    return YES;
//}


// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//
//            NSLog(@"result = %@",resultDic);
//        }];
//    }
//    return YES;
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"zhifuNotification" object:nil userInfo:resultDic];
        }];
    }else{
        
        [WXApi handleOpenURL:url delegate:self];
        [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }
    
    
//    NSString *customURL = @"xiangtaitai://";
//    
// 
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];

    
    return YES;
}


- (void)onResp:(BaseResp *)resp{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        
        SendAuthResp *temp = (SendAuthResp *)resp;
        
        NSDictionary * dict = @{@"code":temp.code};

        [[NetworkTool sharedTools] POST:@"Api/appGetOpenId" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            int code = [responseObject[@"code"] intValue];
     
            if (code == 200) {
                
                NSDictionary * resDict = responseObject[@"data"];
                NSMutableDictionary * mudict = [NSMutableDictionary dictionaryWithDictionary:resDict];
                
                if([[resDict allKeys] containsObject:@"phone"]){
                    
                    NSString * ID = resDict[@"id"];
                    DEF_SET_OBJECT(ID, @"id");
                    
                    MainTabBarController *tabs = [[MainTabBarController alloc] init];
                    
                    self.window.rootViewController = tabs;
                    
                }else{
 
                    [mudict removeObjectForKey:@"privilege"];
                    
                    BoundTelViewController * boundVC = [BoundTelViewController new];
                    
                    boundVC.dict = mudict.copy;
                    
                    self.window.rootViewController = boundVC;
                }
            }
            

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            
        }];
//        NSDictionary * dict = @{@"appid":@"wxe282ff941e1f8a1d",@"secret":@"4d7dea52b20465e333dfe38aaa8b5a61",@"code":temp.code,@"grant_type":@"authorization_code"};
//
//        [[WechatNetwork sharedTools] GET:@"sns/oauth2/access_token" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//            NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
//            NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
//            NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
//            NSString *refreshToken = [accessDict objectForKey:WX_REFRESH_TOKEN];
//            // 本地持久化，以便access_token的使用、刷新或者持续
//            if (accessToken && ![accessToken isEqualToString:@""] && openID && ![openID isEqualToString:@""]) {
//                [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:WX_ACCESS_TOKEN];
//                [[NSUserDefaults standardUserDefaults] setObject:openID forKey:WX_OPEN_ID];
//                [[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:WX_REFRESH_TOKEN];
//                [[NSUserDefaults standardUserDefaults] synchronize]; // 命令直接同步到文件里，来避免数据的丢失
//            }
//
//            [self wechatLoginByRequestForUserInfo];
//
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//        }];
        
    }
//    else if([resp isKindOfClass:[PayResp class]]){
//        //支付返回结果，实际支付结果需要去微信服务器端查询
//        //启动微信支付的response
//        NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
//        switch (resp.errCode) {
//            case 0:
//                payResoult = @"支付结果：成功！";
//                break;
//            case -1:
//                payResoult = @"支付结果：失败！";
//                break;
//            case -2:
//                payResoult = @"用户已经退出支付！";
//                break;
//            default:
//                payResoult = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
//                break;
//        }
//    }
    
}

//手机端获取用户信息
- (void)sendWechatRequestCode{
    

}


//手机端获取用户信息
- (void)wechatLoginByRequestForUserInfo{
    
//    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
//    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
//    
//    [[WechatNetwork sharedTools] GET:@"sns/userinfo" parameters:@{@"openid":openID,@"access_token":accessToken} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        NSLog(@"请求用户信息的response = %@", responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];

}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        
        [[UIApplication alloc] setApplicationIconBadgeNumber:0];
    }else{
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
        UIApplication *app = [UIApplication sharedApplication];
        // 应用程序右上角数字
        app.applicationIconBadgeNumber = 0;
    }
    
    [application cancelAllLocalNotifications];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserLocal" object:nil];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//    [application setApplicationIconBadgeNumber:0];
//    [JMessage resetBadge];
    application.applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSUInteger shouldSelectIndex = [tabBarController.viewControllers indexOfObject:viewController];
    if (tabBarController.selectedIndex == shouldSelectIndex) {
        return YES;
    }
    
    CATransition *animation = [CATransition animation];
//    animation.duration = 0.2;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    if (tabBarController.selectedIndex > shouldSelectIndex) {
        animation.subtype = kCATransitionFromLeft;
    } else {
        animation.subtype = kCATransitionFromRight;
    }
    // 与百度上一般文章不一样
    [[[tabBarController valueForKey:@"_viewControllerTransitionView"] layer] addAnimation:animation forKey:@"animation"];
    
    return YES;
}


@end
